#!/bin/bash

# Copyright (C) 2024 Canonical Ltd.
#
# This file is part of tdx repo. See LICENSE file for license information.

_on_error() {
  trap '' ERR
  line_path=$(caller)
  line=${line_path% *}
  path=${line_path#* }

  echo ""
  echo "ERR $path:$line $BASH_COMMAND exited with $1"
  exit 1
}
trap '_on_error $?' ERR

set -eE

echo "Begin to do setup.sh....."
echo "nameserver 8.8.8.8" > /etc/resolv.conf
apt update

# Utilities packages for automated testing
# linux-tools-common for perf, please make sure that linux-tools is also installed
apt install -y cpuid linux-tools-common msr-tools python3 python3-pip


echo "Begin to do setup.sh....."

# 配置网络为 DHCP
cat > /etc/systemd/network/20-wired.network <<EOF
[Match]
Name=*

[Network]
DHCP=yes
EOF

# 启用 systemd-networkd 服务
systemctl enable systemd-networkd
systemctl enable systemd-resolved


echo "Begin to do setup.sh....."

# 配置 DNS 解析
ln -sf /run/systemd/resolve/stub-resolv.conf /etc/resolv.conf

# setup ssh
# allow password auth + root login
sed -i 's|[#]*PasswordAuthentication .*|PasswordAuthentication yes|g' /etc/ssh/sshd_config
sed -i 's|[#]*PermitRootLogin .*|PermitRootLogin yes|g' /etc/ssh/sshd_config
sed -i 's|[#]*KbdInteractiveAuthentication .*|KbdInteractiveAuthentication yes|g' /etc/ssh/sshd_config
# livecd-rootfs adds 60-cloudimg-settings.conf file to set PasswordAuthentication to no
# if the file exists, remove it
rm -f /etc/ssh/sshd_config.d/60-cloudimg-settings.conf

# Enable TDX
/tmp/tdx/setup-tdx-guest.sh

# Install tools
cd /tmp/tdx/tdx-tools/
python3 -m pip install --break-system-packages ./

rm -rf /tmp/tdx || true

echo "finish to do setup.sh....."
